import { base64Encode, base64Decode } from '../crypto'

const KEY: string = 'SUMMER-SESSION-STORE-'
const debug = false
const encode = debug ? (s: string) => s : base64Encode
const decode = debug ? (s: string) => s : base64Decode

export function setBoolean(key: string, val: boolean) {
  setNumber(key, val ? 1 : 0)
}

export function getBoolean(key: string): boolean {
  const num = getNumber(key)
  return num === 1
}

export function setNumber(key: string, val: number): void {
  const k = encode(String(KEY + key))
  if (val == null) {
    sessionStorage.removeItem(k)
  } else {
    const v = encode(String(val))
    sessionStorage.setItem(k, v)
  }
}

export function getNumber(key: string): number | null {
  try {
    const k = encode(String(KEY + key))
    const val = sessionStorage.getItem(k)
    if (val == null) {
      return null
    }
    return Number(decode(val))
  } catch (e) {
    return null
  }
}

export function setString(key: string, val: string): void {
  const k = encode(String(KEY + key))
  if (val == null) {
    sessionStorage.removeItem(k)
  } else {
    const v = encode(String(val))
    sessionStorage.setItem(k, v)
  }
}

export function getString(key: string): string | null {
  try {
    const k = encode(String(KEY + key))
    const val = sessionStorage.getItem(k)
    if (val == null) {
      return null
    }
    return decode(val)
  } catch (e) {
    return null
  }
}

export function setJson(key: string, val: Record<any, any>): void {
  const k = encode(String(KEY + key))
  if (val == null) {
    sessionStorage.removeItem(k)
  } else {
    const v = encode(JSON.stringify(val))
    sessionStorage.setItem(k, v)
  }
}

export function getJson(key: string): Record<any, any> | null {
  try {
    const k = encode(String(KEY + key))
    const val = sessionStorage.getItem(k)
    if (val == null) {
      return null
    }
    const decodedVal = decode(val)
    if (decodedVal == null) {
      return null
    }
    return JSON.parse(decodedVal)
  } catch (e) {
    return null
  }
}

export function removeItem(key: string): void {
  const k = encode(String(KEY + key))
  sessionStorage.removeItem(k)
}

export function clear(): void {
  sessionStorage.clear()
}
